package com.datacenter.service;

import com.datacenter.entity.*;
import com.datacenter.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 效率分析服务
 * 
 * 业务含义：
 * 实现场景4的资源使用效率分析功能，包括：
 * - 资源活跃度分析：识别沉睡资源和高价值资源
 * - 审批效率分析：统计审批时长、识别审批瓶颈
 * - 资源价值评估：基于使用情况评估资源价值
 */
@Slf4j
@Service
public class EfficiencyAnalysisService {
    
    @Autowired
    private ResourceMetadataMapper resourceMetadataMapper;
    
    @Autowired
    private ApiCallLogMapper apiCallLogMapper;
    
    @Autowired
    private DownloadLogMapper downloadLogMapper;
    
    @Autowired
    private UserApplicationMapper userApplicationMapper;
    
    /**
     * 获取资源活跃度分析
     * 业务含义：分析资源的使用活跃度，识别沉睡资源和高价值资源
     */
    public Map<String, Object> getResourceActivityAnalysis() {
        log.info("开始分析资源活跃度");
        
        Map<String, Object> activityData = new HashMap<>();
        
        // 沉睡资源识别
        List<Map<String, Object>> sleepingResources = identifySleepingResources();
        activityData.put("sleepingResources", sleepingResources);
        
        // 高价值资源识别
        List<Map<String, Object>> highValueResources = identifyHighValueResources();
        activityData.put("highValueResources", highValueResources);
        
        // 资源活跃度统计
        Map<String, Object> activityStats = getResourceActivityStats();
        activityData.put("activityStats", activityStats);
        
        log.info("资源活跃度分析完成");
        return activityData;
    }
    
    /**
     * 获取审批效率分析
     * 业务含义：分析用户申请资源的审批效率，识别审批瓶颈
     */
    public Map<String, Object> getApprovalEfficiencyAnalysis() {
        log.info("开始分析审批效率");
        
        Map<String, Object>> efficiencyData = new HashMap<>();
        
        // 平均审批时长统计
        Map<String, Object> avgApprovalTime = getAverageApprovalTime();
        efficiencyData.put("avgApprovalTime", avgApprovalTime);
        
        // 超时审批统计
        Map<String, Object> overtimeApproval = getOvertimeApprovalStats();
        efficiencyData.put("overtimeApproval", overtimeApproval);
        
        // 按部门统计审批效率
        List<Map<String, Object>> deptApprovalEfficiency = getDepartmentApprovalEfficiency();
        efficiencyData.put("deptApprovalEfficiency", deptApprovalEfficiency);
        
        // 按资源类型统计审批效率
        List<Map<String, Object>> typeApprovalEfficiency = getResourceTypeApprovalEfficiency();
        efficiencyData.put("typeApprovalEfficiency", typeApprovalEfficiency);
        
        log.info("审批效率分析完成");
        return efficiencyData;
    }
    
    /**
     * 获取资源价值评估
     * 业务含义：基于使用情况评估资源价值，为资源优化提供依据
     */
    public Map<String, Object> getResourceValueAssessment() {
        log.info("开始评估资源价值");
        
        Map<String, Object> valueData = new HashMap<>();
        
        // 资源使用价值排行
        List<Map<String, Object>> resourceValueRanking = getResourceValueRanking();
        valueData.put("resourceValueRanking", resourceValueRanking);
        
        // 资源优化建议
        List<Map<String, Object>> optimizationSuggestions = getOptimizationSuggestions();
        valueData.put("optimizationSuggestions", optimizationSuggestions);
        
        // 资源生命周期分析
        Map<String, Object> lifecycleAnalysis = getResourceLifecycleAnalysis();
        valueData.put("lifecycleAnalysis", lifecycleAnalysis);
        
        log.info("资源价值评估完成");
        return valueData;
    }
    
    /**
     * 识别沉睡资源
     * 业务含义：识别接口日均调用<10次、Excel月均下载<5次的沉睡资源
     */
    private List<Map<String, Object>> identifySleepingResources() {
        List<Map<String, Object>> sleepingResources = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        String[] resourceNames = {
            "历史人口数据", "旧版统计报表", "废弃接口数据", 
            "测试数据文件", "临时数据表"
        };
        
        for (int i = 0; i < resourceNames.length; i++) {
            Map<String, Object>> resource = new HashMap<>();
            resource.put("resourceId", i + 1);
            resource.put("resourceName", resourceNames[i]);
            resource.put("resourceType", i % 3 == 0 ? "API" : (i % 3 == 1 ? "DB" : "EXCEL"));
            resource.put("department", "省统计局");
            resource.put("lastUsedTime", LocalDateTime.now().minusDays(getRandomDays(30, 365)));
            resource.put("usageCount", getRandomCount(1, 9));
            resource.put("sleepDuration", getRandomDays(30, 365));
            resource.put("recommendation", "建议归档或删除");
            sleepingResources.add(resource);
        }
        
        return sleepingResources;
    }
    
    /**
     * 识别高价值资源
     * 业务含义：识别调用/下载量Top20%的高价值资源
     */
    private List<Map<String, Object>> identifyHighValueResources() {
        List<Map<String, Object>> highValueResources = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        String[] resourceNames = {
            "广东省GDP统计数据", "企业注册信息查询接口", "人口普查数据",
            "交通流量实时数据", "教育统计数据", "医疗资源分布数据"
        };
        
        for (int i = 0; i < resourceNames.length; i++) {
            Map<String, Object>> resource = new HashMap<>();
            resource.put("resourceId", i + 1);
            resource.put("resourceName", resourceNames[i]);
            resource.put("resourceType", i % 3 == 0 ? "API" : (i % 3 == 1 ? "DB" : "EXCEL"));
            resource.put("department", "省统计局");
            resource.put("usageCount", getRandomCount(1000, 10000));
            resource.put("valueScore", getRandomScore(80, 100));
            resource.put("contributionRatio", getRandomRatio(0.15, 0.25));
            resource.put("recommendation", "重点维护和推广");
            highValueResources.add(resource);
        }
        
        return highValueResources;
    }
    
    /**
     * 获取资源活跃度统计
     * 业务含义：统计不同活跃度级别的资源分布
     */
    private Map<String, Object> getResourceActivityStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 模拟数据，实际应该从数据库查询
        stats.put("totalResources", 1000);
        stats.put("activeResources", 750);
        stats.put("sleepingResources", 200);
        stats.put("inactiveResources", 50);
        
        Map<String, Object> ratios = new HashMap<>();
        ratios.put("activeRatio", 0.75);
        ratios.put("sleepingRatio", 0.20);
        ratios.put("inactiveRatio", 0.05);
        stats.put("ratios", ratios);
        
        return stats;
    }
    
    /**
     * 获取平均审批时长
     * 业务含义：统计不同维度的平均审批时长
     */
    private Map<String, Object> getAverageApprovalTime() {
        Map<String, Object> avgTime = new HashMap<>();
        
        // 模拟数据，实际应该从数据库查询
        avgTime.put("overallAvgHours", 24.5);
        avgTime.put("apiApprovalHours", 18.2);
        avgTime.put("dbApprovalHours", 28.7);
        avgTime.put("excelApprovalHours", 22.1);
        
        Map<String, Object> deptAvgTime = new HashMap<>();
        deptAvgTime.put("省统计局", 20.3);
        deptAvgTime.put("省民政厅", 26.8);
        deptAvgTime.put("省教育厅", 22.1);
        avgTime.put("deptAvgTime", deptAvgTime);
        
        return avgTime;
    }
    
    /**
     * 获取超时审批统计
     * 业务含义：统计超48小时未审批的申请占比
     */
    private Map<String, Object> getOvertimeApprovalStats() {
        Map<String, Object> overtimeStats = new HashMap<>();
        
        // 模拟数据，实际应该从数据库查询
        overtimeStats.put("totalApplications", 1000);
        overtimeStats.put("overtimeApplications", 150);
        overtimeStats.put("overtimeRatio", 0.15);
        
        Map<String, Object> overtimeByType = new HashMap<>();
        overtimeByType.put("API", 0.12);
        overtimeByType.put("DB", 0.18);
        overtimeByType.put("EXCEL", 0.14);
        overtimeStats.put("overtimeByType", overtimeByType);
        
        return overtimeStats;
    }
    
    /**
     * 获取部门审批效率
     * 业务含义：统计各部门的审批效率对比
     */
    private List<Map<String, Object>> getDepartmentApprovalEfficiency() {
        List<Map<String, Object>> deptEfficiency = new ArrayList<>();
        
        String[] departments = {"省统计局", "省民政厅", "省教育厅", "省卫健委"};
        
        for (String dept : departments) {
            Map<String, Object>> deptData = new HashMap<>();
            deptData.put("department", dept);
            deptData.put("avgApprovalHours", getRandomHours(15, 35));
            deptData.put("approvalCount", getRandomCount(100, 500));
            deptData.put("overtimeCount", getRandomCount(10, 50));
            deptData.put("efficiencyScore", getRandomScore(60, 95));
            deptEfficiency.add(deptData);
        }
        
        return deptEfficiency;
    }
    
    /**
     * 获取资源类型审批效率
     * 业务含义：统计不同资源类型的审批效率
     */
    private List<Map<String, Object>> getResourceTypeApprovalEfficiency() {
        List<Map<String, Object>> typeEfficiency = new ArrayList<>();
        
        String[] resourceTypes = {"API", "DB", "EXCEL"};
        
        for (String type : resourceTypes) {
            Map<String, Object>> typeData = new HashMap<>();
            typeData.put("resourceType", type);
            typeData.put("avgApprovalHours", getRandomHours(15, 30));
            typeData.put("approvalCount", getRandomCount(200, 800));
            typeData.put("overtimeCount", getRandomCount(20, 100));
            typeData.put("efficiencyScore", getRandomScore(70, 95));
            typeEfficiency.add(typeData);
        }
        
        return typeEfficiency;
    }
    
    /**
     * 获取资源价值排行
     * 业务含义：基于使用情况对资源进行价值评估和排行
     */
    private List<Map<String, Object>> getResourceValueRanking() {
        List<Map<String, Object>> valueRanking = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        String[] resourceNames = {
            "广东省GDP统计数据", "企业注册信息查询接口", "人口普查数据",
            "交通流量实时数据", "教育统计数据", "医疗资源分布数据",
            "环境监测数据", "就业统计信息", "房地产数据", "金融统计数据"
        };
        
        for (int i = 0; i < resourceNames.length; i++) {
            Map<String, Object>> resource = new HashMap<>();
            resource.put("rank", i + 1);
            resource.put("resourceName", resourceNames[i]);
            resource.put("resourceType", i % 3 == 0 ? "API" : (i % 3 == 1 ? "DB" : "EXCEL"));
            resource.put("valueScore", getRandomScore(85, 100));
            resource.put("usageCount", getRandomCount(5000, 50000));
            resource.put("contributionRatio", getRandomRatio(0.05, 0.20));
            resource.put("trend", getRandomTrend());
            valueRanking.add(resource);
        }
        
        return valueRanking;
    }
    
    /**
     * 获取资源优化建议
     * 业务含义：基于分析结果提供资源优化建议
     */
    private List<Map<String, Object>> getOptimizationSuggestions() {
        List<Map<String, Object>> suggestions = new ArrayList<>();
        
        // 模拟数据，实际应该基于分析结果生成
        suggestions.add(createSuggestion("沉睡资源清理", "发现200个沉睡资源，建议归档或删除", "高"));
        suggestions.add(createSuggestion("审批流程优化", "省民政厅审批效率较低，建议优化流程", "中"));
        suggestions.add(createSuggestion("高价值资源推广", "GDP统计数据使用价值高，建议加大推广力度", "低"));
        suggestions.add(createSuggestion("资源分类管理", "建议按使用频率对资源进行分类管理", "中"));
        
        return suggestions;
    }
    
    /**
     * 获取资源生命周期分析
     * 业务含义：分析资源从创建到废弃的完整生命周期
     */
    private Map<String, Object> getResourceLifecycleAnalysis() {
        Map<String, Object> lifecycle = new HashMap<>();
        
        // 模拟数据，实际应该从数据库查询
        lifecycle.put("newResources", 150); // 新创建资源
        lifecycle.put("activeResources", 750); // 活跃资源
        lifecycle.put("decliningResources", 80); // 使用量下降资源
        lifecycle.put("sleepingResources", 200); // 沉睡资源
        lifecycle.put("archivedResources", 50); // 已归档资源
        
        Map<String, Object> lifecycleTrend = new HashMap<>();
        lifecycleTrend.put("avgLifecycleDays", 365);
        lifecycleTrend.put("peakUsageDays", 90);
        lifecycleTrend.put("declineStartDays", 180);
        
        lifecycle.put("lifecycleTrend", lifecycleTrend);
        
        return lifecycle;
    }
    
    // 辅助方法
    private Map<String, Object> createSuggestion(String title, String description, String priority) {
        Map<String, Object>> suggestion = new HashMap<>();
        suggestion.put("title", title);
        suggestion.put("description", description);
        suggestion.put("priority", priority);
        suggestion.put("createTime", LocalDateTime.now());
        return suggestion;
    }
    
    private int getRandomDays(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
    
    private int getRandomCount(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
    
    private int getRandomHours(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
    
    private int getRandomScore(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
    
    private double getRandomRatio(double min, double max) {
        return min + (max - min) * new Random().nextDouble();
    }
    
    private String getRandomTrend() {
        String[] trends = {"上升", "下降", "稳定"};
        return trends[new Random().nextInt(trends.length)];
    }
}
